/*
 * Copyright 2002-2006 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.tigris.jasmincc.framework.namespace;

import java.io.*;
import java.util.*;
import org.tigris.jasmincc.framework.exception.*;
import org.tigris.jasmincc.utils.StringServices;

/**
 * Manages namespace and file system directory mapping.
 * 
 * @author Sam Huang
 * @see NamespaceManager
 */
public class Namespace extends AbstractNamespace {

	/**
	 * 
	 * @param directory
	 * @return
	 */
	public static Map<String, File> collect(File directory) {
		Map<String, File> entities = new HashMap<String, File>();

		File[] files = directory.listFiles(filter);
		for (File file : files) {
			String grammarName = getName(file);
			entities.put(grammarName, file);
		}
		return entities;
	}

	/**
	 * 
	 * @param file
	 * @return
	 */
	public static String getName(File file) {
		String fileName = file.getName();
		int dot = fileName.lastIndexOf('.');
		String grammarName = fileName.substring(0, dot);
		return grammarName;
	}

	/**
	 * 
	 * @param namespaceName
	 * @param grammarBase
	 * @throws Exception
	 */
	public Namespace(String namespaceName, String grammarBase) throws Exception {
		this.name = namespaceName;
		this.grammarBase = grammarBase;
		File directory = getDirectory(namespaceName);
		entities = collect(directory);
	}

	/**
	 * 
	 * @param namespaceName
	 * @return
	 * @throws Exception
	 */
	public File getDirectory(String namespaceName) throws Exception {
		String fileName = grammarBase
				+ StringServices
						.replace(namespaceName, '.', File.separatorChar);
		File directory = new File(fileName.endsWith(File.separator) ? fileName
				: fileName + File.separator);
		if (directory == null) {
			throw new NamespaceNotFoundException(namespaceName);
		}
		if (!directory.isDirectory()) {
			throw new NamespaceNotFoundException(namespaceName + " ["
					+ fileName + "]");
		}
		return directory;
	}
}
